<?php
/**
 * Created by PhpStorm.
 * Date: 2023/5/06
 * Time: 16:20
 */

namespace App\frontend\models;


use App\common\models\BaseModel;
use Illuminate\Support\Facades\DB;

/**
 * Class AreaModel
 * @package app\common\models
 */
class AreaModel extends BaseModel
{
    public $table = 'area';


    static $_instance; //本类的实例

    public static function getInstance()
    {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * 获取省级地区数据列表
     * @return mixed
     */
    public function getProvince()
    {
        $condition = ['level' => '1'];
        return self::getArea($condition);
    }

    /**
     * 根据条件获取数据
     * @param $condition
     * @return mixed
     */
    public function getArea($condition)
    {
        return self::where($condition)->get();
    }

    /**
     * 获取指定地区数据
     * @param $data
     * @return mixed
     */
    public static function getAddress($data)
    {
        return self::whereIn('id', $data)->get();
    }

    /**
     * 获取所有地区数据
     * @return array
     */
    public static function getAllArea()
    {

        $model = static::orderBy('parentid', 'asc')->get();

        if ($model->isEmpty()) {
            return array();
        }
        return $model->toArray();
    }

    /**
     * 获取地区数据
     * @return array
     */
    public static function getAreaDatas()
    {
        //获取取数
        $datas = self::getAllArea();
        //处理数据
        return self::getInstance()->processingAreaData($datas);
    }

    /**
     * 处理地区数据 省--市--区
     * @param $address
     * @return array
     */
    private function processingAreaData($address)
    {
        if (empty($address)) {
            return [];
        }

        $province = [];
        $city = [];
        $region = [];
        foreach ($address as $val) {
            if ($val['level'] == 1) {
                $province[$val['id']] = $val;
            }
            if ($val['level'] == 2) {
                $city[$val['id']] = $val;
            }
            if ($val['level'] == 3) {
                $region[$val['id']] = $val;
            }
        }

        foreach ($region as $val) {
            $city[$val['parentid']]['list'][] = $val;
        }
        unset($region);
        foreach ($city as $val) {
            $province[$val['parentid']]['list'][] = $val;
        }
        unset($city);
        $Datas = array_values($province);
        unset($province);
        return $Datas;
    }

    /**
     * 保存
     * @param $condition
     * @param $data
     * @return int|void
     */
    public function modifySave($condition, $data)
    {
        $data = DB::table($this->table)->where($condition)->update($data);
        return $data;
    }


}
